package com.zhang.uppdfdemo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 上传PDF文件接口
     * @param file 上传的文件
     * @return 上传结果
     */
    @PostMapping("/upload/pdf")
    public ResponseEntity<Map<String, Object>> uploadPdf(
            @RequestParam("file") MultipartFile file) {

        Map<String, Object> result = new HashMap<>();

        // 检查文件是否为空
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择要上传的PDF文件");
            return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
        }

        // 检查文件类型是否为PDF
        String contentType = file.getContentType();
        if (contentType == null || !contentType.equals("application/pdf")) {
            result.put("success", false);
            result.put("message", "仅支持PDF格式文件上传");
            return new ResponseEntity<>(result, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
        }

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            // 生成唯一文件名（避免重名）
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            // 构建文件保存路径
            Path filePath = Paths.get(uploadPath, uniqueFileName);

            // 保存文件
            Files.write(filePath, file.getBytes());

            // 构建返回结果
            result.put("success", true);
            result.put("message", "文件上传成功");
            result.put("fileName", originalFilename);
            result.put("savedFileName", uniqueFileName);
            result.put("fileSize", file.getSize() + " bytes");
            result.put("savePath", filePath.toString());

            return new ResponseEntity<>(result, HttpStatus.OK);

        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件上传失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}